#!/usr/bin/ruby
require 'gtk2'



require 'uri'
require 'net/http'
Net::HTTP.version_1_2    # おまじない


class URIFetcher
	def initialize(uri_str, user, password, proc)
		Thread.new(uri_str, user,
				password, proc) do |uri_str, user, password, proc|
			begin
				response = fetch(uri_str, user, password)
				proc.call(response.body)
			rescue => e
				p $!
			end
		end
	end

	def fetch(uri_str, user, password, limit = 10)
		raise ArgumentError, 'http redirect too deep' if limit == 0
		uri = URI.parse(uri_str)
		uri.user = user
		uri.password = password
		req = Net::HTTP::Get.new(uri.path)
		req.basic_auth(uri.user, uri.password)
		Net::HTTP.start(uri.host) do |http|
			response = http.request(req)
			case response
				when Net::HTTPSuccess
					then response
				when Net::HTTPRedirection
					then fetch(response['location'], user, password, limit - 1)
			else
				response.error!
			end
		end
	end
end


URIFetcher.new($ARGV[0], $ARGV[1], $ARGV[2], proc{|body| print body })

sleep(50)


exit


require "rexml/document"
require 'digest/md5'


document = REXML::Document.new(File.new("friends_timeline.xml"))


arr = []

document.elements['/statuses/'].each_with_index do |elem, index|
	if elem.class == REXML::Element
		uri = elem.elements['user/profile_image_url'].text
		uri_md5 = Digest::MD5.hexdigest(uri)
		icon_filename = "/tmp/#{uri_md5}"
#		icon_data = fetch(uri).body
#		File.open(icon_filename, "wb") { |st| st << icon_data }
		arr<< {
			:name => elem.elements['user/name'].text ,
			:screen_name => elem.elements['user/screen_name'].text ,
			:text => elem.elements['text'].text ,
			:icon_filename => icon_filename
			}
	end
end

# ↩
# ↬

window = Gtk::Window.new()
window.signal_connect("destroy") { Gtk.main_quit }


vbox = Gtk::VBox.new(false, 3)

menu_bar = Gtk::MenuBar.new()


file_menu = Gtk::Menu.new
edit_menu = Gtk::Menu.new
help_menu = Gtk::Menu.new

file = Gtk::MenuItem.new("File")
edit = Gtk::MenuItem.new("Edit")
help = Gtk::MenuItem.new("Help")

file.submenu = file_menu
edit.submenu = edit_menu
help.submenu = help_menu

menu_bar.append(file)
menu_bar.append(edit)
menu_bar.append(help)

vbox.pack_start(menu_bar, false)

notebook = Gtk::Notebook.new()



class TweetView < Gtk::ScrolledWindow
	def initialize
		super
		self.hscrollbar_policy = Gtk::POLICY_NEVER
		@v_box = Gtk::VBox.new(false, 2)
		self.add_with_viewport(@v_box)
	end

	def make_h_box(t)
		# HBoxを作成
		h_box = Gtk::HBox.new(false, 4)

		# アイコンの読み込みと Gtk::Image の作成
		icon_pixbuf = Gdk::Pixbuf.new(t[:icon_filename], 48, 48)
		icon = Gtk::Image.new(icon_pixbuf)
		bgcolor = icon.style.bg(Gtk::STATE_NORMAL)
		h_box.pack_start(icon, false, false)

		# テキストバッファの作成と内容の作成
		text_buffer = Gtk::TextBuffer.new
		username_tag = text_buffer.create_tag("name",
			{ :weight => Pango::FontDescription::WEIGHT_BOLD } )
		username_tag.instance_variable_set(:@hint_text, t[:screen_name])
		text_buffer.insert(text_buffer.end_iter, "#{t[:name]} ",
							username_tag)
		text_buffer.insert(text_buffer.end_iter, " ");
		reply_tag = text_buffer.create_tag("reply", {})
		reply_tag.instance_variable_set(:@hint_text, "reply to this message")
		text_buffer.insert(text_buffer.end_iter, "↩ ", reply_tag)
		text_buffer.insert(text_buffer.end_iter, " ");
		rt_tag = text_buffer.create_tag("rt", {})
		rt_tag.instance_variable_set(:@hint_text, "retweet this message")
		text_buffer.insert(text_buffer.end_iter, "↬ ", rt_tag)
		text_buffer.insert(text_buffer.end_iter, "\n#{t[:text]}")

		# TextView の作成
		text_view = Gtk::TextView.new(text_buffer)
		text_view.wrap_mode = Gtk::TextTag::WRAP_CHAR
		text_view.modify_base(Gtk::STATE_NORMAL, bgcolor)
		text_view.modify_base(Gtk::STATE_ACTIVE, bgcolor)
		text_view.modify_base(Gtk::STATE_PRELIGHT, bgcolor)
		text_view.modify_base(Gtk::STATE_INSENSITIVE, bgcolor)

		# TextView 上でマウスカーソルが移動した時のイベントハンドラ
		text_view.signal_connect("motion-notify-event") do |w,e|
			tip = nil
			text_view.get_iter_at_location(e.x, e.y).tags.each do |tag|
				if	tag.name == "name" ||
						tag.name == "reply" ||
						tag.name == "rt"
					tip = tag.instance_variable_get(:@hint_text)
				end
			end

			if tip != nil
				text_view.set_tooltip_text(tip);
				text_view.get_window(Gtk::TextView::WINDOW_TEXT).
					set_cursor(Gdk::Cursor.new(Gdk::Cursor::HAND2))
			else
				text_view.set_tooltip_text(nil);
				text_view.get_window(Gtk::TextView::WINDOW_TEXT).
					set_cursor(Gdk::Cursor.new(Gdk::Cursor::XTERM))
			end
			false
		end
		h_box.pack_start(text_view, true, true)

		h_box
	end

	def set_tweet_data(arr)
		arr.each_with_index do |t, i|
			# ツイートとツイートの間にセパレータを挿入
			if i != 0
				sep = Gtk::HSeparator.new
				@v_box.pack_start(sep, false, true)
			end


			# HBox を VBoxに追加
			@v_box.pack_start(make_h_box(t), false, true)
		end
	end

end




main_tweet_view = TweetView.new
main_tweet_view.set_tweet_data(arr)
notebook.append_page(main_tweet_view, Gtk::Label.new("Messages"))
#notebook.append_page(replies_icon_view, Gtk::Label.new("Replies"))
vbox.add(notebook)

status_bar = Gtk::Statusbar.new()
status_bar.push(status_bar.get_context_id("status"), "test")

vbox.pack_start(status_bar, false)
window.add(vbox)


window.set_size_request(250, 360)

window.title = "つるぺったー"



window.show_all
Gtk.main

